package org.njo.webapp.root.servlet.wrapper;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.njo.webapp.root.model.RemoteUser;

/**
 * Request包装,重写getRemoteUser().
 *  
 * @author yu.peng
 */
public class RemoteUserRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 为了方便EL使用,这里定义了简单的'remoteUser'作为,用户对象存放在session的key.
     */
    public final static String USER_SESSION_KEY = "remoteUser";

    /**
     * 为了方便EL使用,这里定义了简单的'message'作为,消息对象存放在request的key.
     */
    public final static String MESSAGE_KEY = "message";
    
    /**
     * 为了使jsp页面能够取得准确的path(以[/]结尾),覆盖父类的方法.
     */
    public String getContextPath() {
        String contextPath = super.getContextPath();
        if (contextPath.endsWith("/")) {
            contextPath  = contextPath.substring(0, contextPath.length()-1);
            // contextPath  = contextPath + "/"; 
        }
        return contextPath;
    }

    /**
     * 构造方法. 
     * @param request
     */
    public RemoteUserRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * 取得登录的用户的用户名.
     */
    public String getRemoteUser() {
        HttpSession session = super.getSession();
        RemoteUser remoteUser = (RemoteUser) session.getAttribute(USER_SESSION_KEY);
        if (remoteUser!=null) {
            return remoteUser.getName();
        } else {
            return null;
        }
    }
    
    /**
     * 判定指定的该用户时候属于指定的角色.
     * 
     */
    public boolean isUserInRole(String roles) {
        HttpSession session = super.getSession();
        RemoteUser remoteUser = (RemoteUser) session.getAttribute(USER_SESSION_KEY);
        if (remoteUser!=null) {
            return remoteUser.isInRole(roles);
        } else {
            return false;
        }        
    }

    /**
     * 取得用户信息.
     * @return 返回用户对象
     */
    public RemoteUser getRemoteUserAsObject() {
        HttpSession session = super.getSession();
        RemoteUser remoteUser = (RemoteUser) session.getAttribute(USER_SESSION_KEY);
        return remoteUser;
    }

    
    
    /**
     * 取得(Struts)Locale.
     * 
     * @return Locale对象
     */
    public Locale getLocale() {
        Locale userLocale = null;
        HttpSession session = this.getSession(false);

        // Only check session if sessions are enabled
        if (session != null) {
            userLocale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
        }

        if (userLocale == null) {
            // Returns Locale based on Accept-Language header or the server default
            userLocale = super.getLocale();
        }

        return userLocale;
    }

}
